const $_GET = getUrlInfo();

const COLLECTION_LABEL_LIST_API = window.CONFIG.API + '/collect/showInfo';
const COLLECTION_ADD_API = window.CONFIG.API + '/collect/share';
const COLLECTION_CANCEL_API = window.CONFIG.API + '/collect/cancel_share';

const EVENT_ENTER = 13;

let allTags = [];
let alreadyTags = []; // 已收藏的标签

let debounceTimer = null;

$(function () {
  if (!$('input[name="title"]').val()) {
    $('input[name="title"]').val($_GET['title']);
  }

  setTimeout(function () {
    document.getElementById("title").focus();
  }, 300);

  // 输入即搜索
  $('input[name="search_tag"]').on('input', function (e) {
    // 防抖
    if (debounceTimer !== null) clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      rednerCollectTags($.trim($('input[name="search_tag"]').val()));
    }, 500);
  });
  // 取消搜索
  $('.taosha-input-clear').click(function () {
    if ($.trim($('input[name="search_tag"]').val())) {
      $('input[name="search_tag"]').val('');
      rednerCollectTags();
    }
  });

  // 已选标签修改联动
  $('input[name="selected_tags"]').keydown(function (e) {
    // 防抖
    if (debounceTimer !== null) clearTimeout(debounceTimer);
    debounceTimer = setTimeout(() => {
      switchActiveTag();
    }, 500);
  });

  // 点击收藏
  $('#collection-conform').click(function () {
    addCollection();
  });
  // 回车收藏
  $('body').keydown(function (e) {
    if (e.keyCode === 13) {
      addCollection();
    }
  });
  // 点取消
  $('#cancel').click(function () {
    window.parent.postMessage('cancel', $_GET['url']);
  });
  // 点取消收藏
  $('#cancel-collect').click(function () {
    console.log('取消收藏');
    cancelCollection();
    // window.parent.postMessage('cancelCollect', $_GET['url']);
  });

  // 退出登录
  $('button[class="logout-button"]').click(function () {
    logout();
  });
});

const token = localStorage.getItem('userId');
if (token) {
  collectionLabelsList(token);
} else {
  // window.parent.postMessage('clearTimeout', $_GET['url']);
  window.parent.postMessage('loginRequest', $_GET['url']);
}

// API 收藏提交
function addCollection() {
  const title = $('input[name="title"]').val(); // 收藏标题
  const collectUrl = $_GET['url']; // 收藏的链接
  let collectTags = $.trim($('input[name="selected_tags"]').val());
  collectTags = collectTags.trim().replace(/\s+/g, ' ');
  const breif = $('input[name="brief"]').val() || '';
  const topicId = $('input[name="topic_id"]').val(); // 当修改已收藏页面时，再提交就是修改
  const intro = '';
  const isPublic = !$('#is_public').is(':checked');
  console.log('哈哈哈', title);
  if (!title) {
    showToast('收藏标题不能为空');
    return;
  }
  if (collectTags && collectTags.split(' ').length > 5) {
    showToast('最多5个标签');
    return;
  }

  $.ajax({
    url: COLLECTION_ADD_API,
    type: 'post',
    data: {
      access_token: token,
      tab: 'share',
      title: title,
      content: collectUrl,
      original_url: collectUrl,
      // intro: $('input[name="intro"]').val() || '',
      is_public: isPublic,
      collect_tags: collectTags,
      brief: breif,
      topic_id: topicId
    },
    success: function (res) {
      if (res.status === 'success') {
        window.parent.postMessage('collectSuccess', $_GET['url']);
      } else {
        showToast('收藏出错了');
      }
    },
    error: function (error) {
      console.log('添加收藏错误', error);
      if (error.responseJSON && error.responseJSON.error_msg) {
        showToast(error.responseJSON.error_msg);
      } else {
        showToast('收藏出错了');
      }
    }
  });
}

// API 取消收藏
function cancelCollection() {
  $.ajax({
    url: COLLECTION_CANCEL_API,
    type: 'post',
    data: {
      access_token: token,
      topic_id: $('input[name="topic_id"]').val()
    },
    success: function (res) {
      if (res.status === 'success') {
        window.parent.postMessage('cancelCollect', $_GET['url']);
      } else {
        showToast('取消收藏错误');
      }
    },
    error: function (error) {
      console.log('取消收藏错误', error);
      if (error.responseJSON && error.responseJSON.message) {
        showToast(error.responseJSON.message);
      } else {
        showToast('取消收藏错误');
      }
    }
  });
}

// API 拥有的收藏标签列表
function collectionLabelsList() {
  $.ajax({
    url: COLLECTION_LABEL_LIST_API,
    type: 'post',
    data: {
      original_url: $_GET['url'],
      access_token: token
    },
    success: function (res) {
      console.log('收藏列表', res);
      if (res.status === 'success') {
        initCollectionPanel(res.data);
      } else {
        console.log('收藏标签列表错误2', res);
      }
    },
    error: function (error) {
      console.log('收藏标签列表错误', error);
    }
  });
}

function initCollectionPanel(data) {
  const title = data.title;
  const brief = data.brief;
  const isPublic = data.is_public;
  const topicId = data.topic_id;
  allTags = data.userAllTags;
  alreadyTags = data.alreadyTags ? data.alreadyTags.map(item => item.name) : [];

  if (title) {
    $('input[name="title"]').val(title);
  }
  if (brief) {
    $('input[name="brief"]').val(brief);
  }

  if (topicId) {
    $('input[name="topic_id"]').val(topicId);
    $('.collected-icon').css('display', 'block'); // 添加已收藏标志
    $('.cancel-collect').css('display', 'block'); // 添加取消收藏按钮
  }

  if (alreadyTags.length) {
    $('input[name="selected_tags"]').val(alreadyTags.join(' '));
  }
  $('input[name="is_public"]').attr('checked', !isPublic);

  rednerCollectTags();
}

// 渲染标签
function rednerCollectTags(searchTagStr) {
  const labelListDom = $('#collect-tag-list');

  labelListDom.empty();

  let renderTags = allTags;
  if (searchTagStr) {
    renderTags = renderTags.filter(item => item.name.indexOf(searchTagStr) > -1);
  }

  if (renderTags.length) {
    for (const tag of renderTags) {
      let classNameStr = 'label-item';
      if (alreadyTags.indexOf(tag.name) > -1) {
        classNameStr += ' label-active-item';
      }

      labelListDom.append(`<div 
                            class="${classNameStr}" 
                          class="${classNameStr}" 
                            class="${classNameStr}" 
                            title="${tag.name}" 
                          title="${tag.name}" 
                            title="${tag.name}" 
                            onclick="chooseTag('${tag.name}', this)"
                            data-id="${tag._id}">
                              <span>${tag.name}</span>
                              <i>${tag.topics_size}</i>
                            </div>`);
    }
  } else {
    labelListDom.append(`<span class="no-tags-tip">没有符合条件的标签<span>`);
  }

}

// 点击标签选择或取消标签
function chooseTag(tagName, tagDom) {
  let readytoValue = null;
  tagName = $.trim(tagName);

  var selectedTagInputDom = $('input[name="selected_tags"]');
  var selectedTags = selectedTagInputDom.val().trim();

  if (selectedTags) {
    var selectdTagsArr = selectedTags.split(/\s+/);
    if (selectdTagsArr.indexOf(tagName) > -1) {
      selectdTagsArr = selectdTagsArr.filter(name => name !== tagName);
      tagDom.classList.remove('label-active-item');
    } else {
      selectdTagsArr.push(tagName);
      tagDom.classList.add('label-active-item');
    }
    readytoValue = $.trim(selectdTagsArr.join(' '));
  } else {
    readytoValue = tagName;
    tagDom.classList.add('label-active-item');
  }

  selectedTagInputDom.val(readytoValue + ' ');
  document.getElementById('j_taosha_selected_tags').focus();
}

function switchActiveTag() {
  const selectedTagInputDom = $('input[name="selected_tags"]');
  let selectedTags = selectedTagInputDom.val();
  ;

  if (selectedTags) {
    alreadyTags = selectedTags.split(' ');


    console.log('所有的标签', allTags)
    console.log('已选择标签', alreadyTags)
    const allTagsDom = $('#collect-tag-list');
    console.log(allTagsDom.children())

    rednerCollectTags()

    // allTagsDom.children().each(function () {
    //   console.log($(this).children('span').get(0).innerText);
    //   const tagName = $(this).children('span').get(0).innerText;

    //   // if (selectdTagsArr.indexOf(tagName) > -1) {
    //   //   this.classList.remove('label-active-item');
    //   // } else {
    //   //   this.classList.add('label-active-item');
    //   // }
    // });
  }
}

function logout() {
  localStorage.removeItem('userId');
  window.parent.postMessage('logout', $_GET['url']);
}
